package com.hxd.otc.module.order.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.module.order.contract.AlipayQRContract;
import com.hxd.otc.module.order.presenter.AlipayQRPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.FileUtils;
import com.hxd.otc.utils.GlideUtils;
import com.hxd.otc.utils.UIUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 包  名 :  com.hxd.otc.module.order
 * 类  名 : SaleOrderDetailActivity
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${} 保存支付宝二维码页面
 */
public class AlipayQRcodeActivity extends PermissionActivity<AlipayQRPresenter> implements AlipayQRContract.View {

    @BindView(R.id.iv_qrcode)
    ImageView ivQrcode;

    String alipayAddress;
    int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_alipay_qrcode;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        alipayAddress = getIntent().getExtras().getString("alipayAddress");
        type = getIntent().getExtras().getInt("type");
        if (alipayAddress.contains("http") || alipayAddress.contains("https")) {
            GlideUtils.loadNormal(this, alipayAddress, ivQrcode);
        } else {
            alipayAddress = UIUtils.getServiceImageUrlByPath(alipayAddress);
            GlideUtils.loadNormal(this, alipayAddress, ivQrcode);
        }
    }

    @Override
    protected void initEvent() {

    }

    @OnClick(R.id.right_tv)
    public void onClickEvent(View view) {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                savePicture();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {

                dismissSpinnerDlg();
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                dismissSpinnerDlg();
            }

            @Override
            public void onLowVersion() {
                savePicture();
            }
        }, SaleOrderDetailActivity.EXTERNAL_PERMISSION);
    }

    Disposable mDisposable;

    public void savePicture() {

        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
                if (TextUtils.isEmpty(alipayAddress) || FileUtils.getHttpBitmap(alipayAddress) == null){
                    showToast(getString(R.string.image_save_fail));
                }else {
                    emitter.onNext(FileUtils.getHttpBitmap(alipayAddress));
                }

            }
        }).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<Bitmap>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
                showSpinnerDlg(getString(R.string.please_wait), true);
            }

            @Override
            public void onNext(@NonNull Bitmap bitmap) {
                saveAddress(bitmap);
            }

            @Override
            public void onError(Throwable e) {
                dismissSpinnerDlg();
            }

            @Override
            public void onComplete() {
                dismissSpinnerDlg();
            }
        });

    }

    private void saveAddress(@NonNull Bitmap bitmap) {
        if (bitmap.getByteCount() > 0) {
            mPresenter.savePicture(bitmap, FileUtils.getFileName(alipayAddress));
        } else {
            dismissSpinnerDlg();
        }
    }

    @Override
    protected AlipayQRPresenter createPresenter() {
        return new AlipayQRPresenter(this);
    }


    @Override
    public void onSaveSucced() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissSpinnerDlg();
                showToast(getString(R.string.save_success));
                if (type == 1) {//weixin
                    try {
                        showToast(getString(R.string.to_pay));
                        Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                        startActivity(intent);
                    } catch (Exception e) {
                        //若无法正常跳转，在此进行错误处理
                        showToast(getString(R.string.saved_pictuer));
                    }
                } else {//alipay
                    try {
                        showToast(getString(R.string.to_pay));
                        String intentFullUrl = "alipayqr://platformapi/startapp?saId=10000007";
                        Intent intent = Intent.parseUri(intentFullUrl, Intent.URI_INTENT_SCHEME);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //若无法正常跳转，在此进行错误处理
                        showToast(getString(R.string.saved_pictuer_alipay));
                    }
                }

            }
        });
    }

    @Override
    public void onSaveFaild(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissSpinnerDlg();
                showToast(str);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
